package javacommon.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 存放在MDC中的数据，log4j可以直接引用并作为日志信息打印出来.
 * <pre>
 * 示例使用:
 * log4j.appender.stdout.layout.conversionPattern=%d [%X{loginUserId}/%X{req.remoteAddr}/%X{req.id} - %X{req.requestURI}?%X{req.queryString}] %-5p %c{2} - %m%n
 * </pre>
 * @author zzh
 */
@SuppressWarnings("unchecked")
public class LoggerMDCFilter extends OncePerRequestFilter implements Filter{
    
    protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain chain)throws ServletException,IOException {
        try {
            //示例为一个固定的登陆用户,请直接修改代码
            MDC.put("loginUserId", "demo-loginUsername");
            String uri = StringUtils.defaultString(request.getRequestURI());
            String basePath = request.getContextPath();
            ///LIMS/login.do
            //权限验证  
            if((uri.indexOf(".do")>-1 || uri.indexOf(".dwr")>-1) && uri.indexOf("login.do")==-1 && uri.indexOf("loginOut.do")==-1) {
            	Object obj = request.getSession().getAttribute("user");
            	if(obj==null) { //session
            		if(isAjaxRequest(request)) {
            			this.responseOutWithJson(response,"{\"success\":true,\"msg\":\"登录超时,请重新登录。\",\"rows\":[],\"url\":\""+basePath+"/Login.jsp\"}");
            		} else {
            			response.sendRedirect(basePath+"/commons/sessionOut.jsp");
            		}
            		return ;
            	} else { //权限
            		
            	}
            }
            MDC.put("req.requestURI", uri);
            MDC.put("req.queryString", StringUtils.defaultString(request.getQueryString()));
            MDC.put("req.requestURIWithQueryString", request.getRequestURI() + (request.getQueryString() == null ? "" : "?"+request.getQueryString()));
            MDC.put("req.remoteAddr", StringUtils.defaultString(request.getRemoteAddr()));
            //为每一个请求创建一个ID，方便查找日志时可以根据ID查找出一个http请求所有相关日志
            MDC.put("req.id", StringUtils.remove(UUID.randomUUID().toString(),"-")); 
            chain.doFilter(request, response);
        }finally {
            clearMDC();
        }
    }

    
	private void clearMDC() {
        Map map = MDC.getContext();
        if(map != null) {
            map.clear();
        }
    }
	
	/**
	 * 以JSON格式输出
	 * @param response
	 */
	protected void responseOutWithJson(HttpServletResponse response,String jsonStr) {
		response.setCharacterEncoding("UTF-8");
		//response.setContentType("application/json; charset=utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append(jsonStr);
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}
	}
	
	/**
	 * * 判断是否为Ajax请求 * 
	 * @param request HttpServletRequest * 
	 * @return 是true, 否false
	 */
	public boolean isAjaxRequest(HttpServletRequest request) {
		String requestType = request.getHeader("X-Requested-With");
		if (requestType != null && requestType.equals("XMLHttpRequest")) {
			return true;
		} else {
			return false;
		}
	}

}
